//1.引入
const express = require("express");
const { Person } = require("./4-db");
//2.创建
const app = express();
app.use(express.json()); // 解析json数据

app.get("/", async (req, res) => {
  const data = await Person.find({}).sort({ _id: -1 }); // 查找所有的数据
  res.json(data);
});

app.post("/", async (req, res) => {
  const data = new Person(req.body); // 创建实例
  if (req.body.name) {
    await data.save();
    res.json({
      code: 1,
      data: "保存成功",
    });
  } else {
    res.json({
      code: 0,
      data: "不行，name得有",
    });
  }
});
//3.
app.listen("3000", () => {
  console.log("服务器运行在3000端口");
});
